//
//  JSTInterestcircleViewController.m
//  KYKJPackDemo
//
//  Created by 01 on 17/5/8.
//  Copyright © 2017年 ???. All rights reserved.
//

#import "JSTInterestcircleViewController.h"
#import "JSTPublishViewController.h"
#import "JSTInterestcircleDataFrame.h"
#import "JSTInterestcircleDataModel.h"
#import "JSTInterestcircleCell.h"
#import "JSTCommentViewController.h"
#import "KYNavigationController.h"
#import "KYLoginController.h"

#define kNewStatus      @"new"
#define kHotStatus      @"hot"

@interface JSTInterestcircleViewController ()<UITableViewDelegate, UITableViewDataSource, JSTInsterestcircleCellDelegate>

@property (nonatomic, strong) UITableView *tabVeiw;

@property (nonatomic, strong) UIView *titleView;

@property (nonatomic, strong) UIButton *titleLeftBtn;

@property (nonatomic, strong) UIButton *titleRightBtn;

@property (nonatomic, strong) UIView *titleFootView;

@property (nonatomic, strong) UIScrollView *scrollView;

/**
 最热列表
 */
@property (nonatomic, strong) UITableView *thehottestTabVeiw;

/**
 最新列表
 */
@property (nonatomic, strong) UITableView *thelatestTabView;

/**
 最热数据
 */
@property (nonatomic, strong) NSMutableArray *thehottestData;

/**
 最新数据
 */
@property (nonatomic, strong) NSMutableArray *thelatestData;

/**
 最热frame
 */
@property (nonatomic, strong) NSMutableArray *thehottestDataFrame;

/**
 最新frame
 */
@property (nonatomic, strong) NSMutableArray *thelatestDataFrame;

@property (nonatomic, strong) NSMutableArray *data;

@property (nonatomic, strong) NSMutableArray *dataFrame;

@property (nonatomic, assign) NSInteger newPageIndex;

@property (nonatomic, assign) NSInteger newPageSize;

@property (nonatomic, assign) NSInteger hotPageIndex;

@property (nonatomic, assign) NSInteger hotPageSize;

@property (nonatomic, assign) BOOL isFirstLoadHotList;

@property (nonatomic, strong) UIImageView *leftFailImageView;

@property (nonatomic, strong) UIImageView *rightFailImageView;

@end

@implementation JSTInterestcircleViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
        
    // 0.创建所有的子控件
    [self setUpAllSubViews];
    
    // 1.创建右上角编辑按钮
    [self setUpRightNavBarItem];
    
    // 2.设置基本请求数据&创建数组
    [self setUpDataAndArrs];
    
    // 3.是否第一次加载最热
    _isFirstLoadHotList = YES;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self leftRefreshData];
    [self rightRefreshData];
}

#pragma mark - 创建所有的子控件
- (void)setUpAllSubViews
{
    [self.view addSubview:self.titleView];
    [self.view addSubview:self.scrollView];
    
    [self.scrollView addSubview:self.thelatestTabView];
    [self.scrollView addSubview:self.thehottestTabVeiw];
    
    [self.thelatestTabView addSubview:self.leftFailImageView];
    [self.thehottestTabVeiw addSubview:self.rightFailImageView];
    
    self.leftFailImageView.hidden = YES;
    self.rightFailImageView.hidden = YES;
    
    [self.thelatestTabView headerBeginRefreshing];
}

#pragma mark - 创建导航栏右边发布动态按钮按钮
- (void)setUpRightNavBarItem
{
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"navigationbar_addmemo_normal" higlightedImage:@"navigationbar_addmemo_highlight" target:self action:@selector(jumpToComposeVc)];
}

#pragma mark - 设置基本请求数据&创建数组
- (void)setUpDataAndArrs
{
    _newPageSize = 5;
    _newPageIndex = 1;
    _hotPageSize = 5;
    _hotPageIndex = 1;
    
    _thelatestDataFrame = [NSMutableArray array];
    _thehottestDataFrame = [NSMutableArray array];
}

#pragma mark - 根据关键字发送请求获取动态数据
- (void)requestListData:(NSString *)ListStatus
{
    if ([ListStatus isEqualToString:kNewStatus]) { // 最新
        
        // 配置请求参数
        NSString *page = [NSString stringWithFormat:@"%ld", _newPageIndex];
        NSString *size = [NSString stringWithFormat:@"%ld", _newPageSize];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:kNewStatus forKey:@"order"];
        [dic setValue:page forKey:@"page"];
        [dic setValue:size forKey:@"pageSize"];
        
        // 发送请求
        [JSTNewServer requestAllDynamic:dic success:^(NSDictionary *dataDic) { // 请求成功
            
            KYLog(@"listData = %@", dataDic);
            
            // 移除所有刷新
            [self.thelatestTabView footerEndRefreshing];
            [self.thelatestTabView headerEndRefreshing];
            [self createNewFrame:(NSArray *)dataDic];
        } error:^(NSString *errStr) { // 请求失败
            
            KYLog(@"%@", errStr);
            
            // 移除所有刷新
            [self.thelatestTabView footerEndRefreshing];
            [self.thelatestTabView headerEndRefreshing];
            
            // dataFrame移除所有元素
            [_thelatestDataFrame removeAllObjects];
            // 左边失败的iamgeView显示
            self.leftFailImageView.hidden = NO;
            // 刷新表格
            [self.tabVeiw reloadData];
        }];
    } else if ([ListStatus isEqualToString:kHotStatus]) { // 最热
        NSString *page = [NSString stringWithFormat:@"%ld", _hotPageIndex];
        NSString *size = [NSString stringWithFormat:@"%ld", _hotPageSize];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:kHotStatus forKey:@"order"];
        [dic setValue:page forKey:@"page"];
        [dic setValue:size forKey:@"pageSize"];
        
        _isFirstLoadHotList = NO;
        
        [JSTNewServer requestAllDynamic:dic success:^(NSDictionary *dataDic) {
            
            KYLog(@"listData = %@", dataDic);
            
            // 移除所有刷新
            [self.thehottestTabVeiw footerEndRefreshing];
            [self.thehottestTabVeiw headerEndRefreshing];
            
            [self createHotFrame:(NSArray *)dataDic];
            
        } error:^(NSString *errStr) {
            KYLog(@"--- %@", errStr);
            
            // 移除所有刷新
            [self.thehottestTabVeiw footerEndRefreshing];
            [self.thehottestTabVeiw headerEndRefreshing];
            
            [_thehottestDataFrame removeAllObjects];
            self.rightFailImageView.hidden = NO;
            
            // 刷新表格
            [self.tabVeiw reloadData];
        }];
    }
}

/**
 遍历出最新frame集合
 
 @param data 最新数据
 */
- (void)createNewFrame:(NSArray *)data
{
    if (_newPageIndex == 1) {
        _thelatestDataFrame = [NSMutableArray array];
    }
    [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [_thelatestDataFrame addObject:[self getModel:obj]];
    }];
    
    [_thelatestTabView reloadData];
    
    self.leftFailImageView.hidden = IsArrEmpty(_thelatestDataFrame) ? NO : YES;
}

/**
 遍历最热frame集合
 
 @param data 最热数据
 */
- (void)createHotFrame:(NSArray *)data
{
    if (_hotPageIndex == 1) {
        _thehottestDataFrame = [NSMutableArray array];
    }
    [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [_thehottestDataFrame addObject:[self getModel:obj]];
    }];

    [_thehottestTabVeiw reloadData];
    
    self.leftFailImageView.hidden = IsArrEmpty(_thehottestDataFrame) ? NO : YES;
}

- (JSTInterestcircleDataFrame *)getModel:(id)obj
{
    JSTInterestcircleDataModel *model   = [[JSTInterestcircleDataModel alloc] init];
    
    model.timeText                      = [KYHandleDataTool getStr:[obj valueForKey:@"addtime"]];
    model.contentText                   = [KYHandleDataTool getStr:[obj valueForKey:@"content"]];
    model.contentImgUrlArr              = [obj valueForKey:@"imglist"];
    model.dynamicId                     = [KYHandleDataTool getStr:[obj valueForKey:@"id"]];
    model.pointPraise                   = [KYHandleDataTool getStr:[obj valueForKey:@"zan_count"]];
    model.commentNumber                 = [KYHandleDataTool getStr:[obj valueForKey:@"discuss_count"]];
    model.iconImgUrl                    = [KYHandleDataTool getStr:[obj valueForKey:@"icon"]];
    model.userName                      = [KYHandleDataTool getStr:[obj valueForKey:@"nickname"]];
    model.praiseStatus                  = [[KYHandleDataTool getStr:[obj valueForKey:@"is_zan"]] boolValue];
    
    JSTInterestcircleDataFrame *dataFrame = [[JSTInterestcircleDataFrame alloc] init];
    dataFrame.model = model;
    return dataFrame;
}

#pragma mark - tabView的数据源&代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.thelatestTabView) {
        return _thelatestDataFrame.count;
    } else {
        return _thehottestDataFrame.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _thelatestTabView) {
        JSTInterestcircleCell *latestCell;
        if (!latestCell) {
            latestCell = [[JSTInterestcircleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"latestCell"];
        }
        latestCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if (tableView == self.thelatestTabView) {
            latestCell.dataFrame = [self.thelatestDataFrame safeObjectAtIndex:indexPath.section];
        } else {
            latestCell.dataFrame = [self.thehottestDataFrame safeObjectAtIndex:indexPath.section];
        }
        
        latestCell.delegate = self;
        
        return latestCell;
    } else {
        JSTInterestcircleCell *hotCell;
        if (!hotCell) {
            hotCell = [[JSTInterestcircleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"hotCell"];
        }
        hotCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if (tableView == self.thelatestTabView) {
            hotCell.dataFrame = [self.thelatestDataFrame safeObjectAtIndex:indexPath.section];
        } else {
            hotCell.dataFrame = [self.thehottestDataFrame safeObjectAtIndex:indexPath.section];
        }
        
        hotCell.delegate = self;
        
        return hotCell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.thelatestTabView) {
        JSTInterestcircleDataFrame *dataFrame = [_thelatestDataFrame safeObjectAtIndex:indexPath.section];
        return dataFrame.cellHeight;
    } else {
        JSTInterestcircleDataFrame *dataFrame = [_thehottestDataFrame safeObjectAtIndex:indexPath.section];
        return dataFrame.cellHeight;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.thelatestTabView) {
        JSTInterestcircleDataFrame *dataFrame = [_thelatestDataFrame safeObjectAtIndex:indexPath.section];
        [self onclickChangePage:dataFrame.model.dynamicId];
    } else if (tableView == self.thehottestTabVeiw) {
        JSTInterestcircleDataFrame *dataFrame = [_thehottestDataFrame safeObjectAtIndex:indexPath.section];
        [self onclickChangePage:dataFrame.model.dynamicId];
    }
}

#pragma mark - cell分割线到头
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - scrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.scrollView.contentOffset.x == kScreenWidth) {
        [self changeRightPage];
    } else {
        [self changeLeftPage];
    }
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (IOS7_OR_LATER && [self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

#pragma mark - method事件处理
/**
 *  跳转到发布控制器
 */
- (void)jumpToComposeVc
{
    if (![KYUserAccountTool shareUserData].token) {
        KYLoginController *loginVc = [[KYLoginController alloc] init];
        KYNavigationController *nav = [[KYNavigationController alloc] initWithRootViewController:loginVc];
        [self presentViewController:nav animated:YES completion:nil];
    } else {
        JSTPublishViewController *pushVc = [[JSTPublishViewController alloc] init];
        KYNavigationController *nav = [[KYNavigationController alloc] initWithRootViewController:pushVc];
        [self presentViewController:nav animated:YES completion:nil];
    }
}

/**
 *  切换到最新列表
 */
- (void)changeLeftPage
{
    [UIView animateWithDuration:0.35 animations:^{
        [self.scrollView setContentOffset:CGPointMake(0, 0)];
        _titleFootView.centerX = _titleLeftBtn.centerX;
        _titleLeftBtn.selected = YES;
        _titleRightBtn.selected = NO;
    }];
}

/**
 *  切换到最热列表
 */
- (void)changeRightPage
{
    [UIView animateWithDuration:0.35 animations:^{
        [self.scrollView setContentOffset:CGPointMake(kScreenWidth, 0)];
        _titleFootView.centerX = _titleRightBtn.centerX;
        _titleLeftBtn.selected = NO;
        _titleRightBtn.selected = YES;
    }];
    
    // 如果第一次加载发送请求
    if (_isFirstLoadHotList)
    {
        [self.thehottestTabVeiw headerBeginRefreshing];
    }
}

/**
 *  跳转到动态详情
 */
- (void)onclickChangePage:(NSString *)dynamicId
{
    JSTCommentViewController *commentVc = [[JSTCommentViewController alloc] init];
    commentVc.dynamicId = dynamicId;
    [self.navigationController pushViewController:commentVc animated:YES];
}

- (void)onclickPraise:(NSString *)comentId
{
    
}

#pragma mark - 懒加载创建所有的视图
- (UIView *)titleView
{
    if (!_titleView) {
        //0.整体的标题view
        _titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kCurrentScreenWidth(30))];
        
        //1.最新标题Button
        _titleLeftBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth/2, _titleView.height - kCurrentScreenWidth(2))];
        [_titleLeftBtn setTitle:@"最 新" forState:UIControlStateNormal];
        [_titleLeftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_titleLeftBtn setTitleColor:KYColor(237, 106, 45, 1.0) forState:UIControlStateSelected];
        [_titleLeftBtn addTarget:self action:@selector(changeLeftPage) forControlEvents:UIControlEventTouchUpInside];
        _titleLeftBtn.selected = YES;
        [_titleView addSubview:_titleLeftBtn];
        
        //2.最热标题Button
        _titleRightBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_titleLeftBtn.frame), 0, _titleLeftBtn.width, _titleLeftBtn.height- kCurrentScreenWidth(2))];
        [_titleRightBtn setTitle:@"最 热" forState:UIControlStateNormal];
        [_titleRightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_titleRightBtn setTitleColor:KYColor(237, 106, 45, 1.0) forState:UIControlStateSelected];
        _titleRightBtn.selected = NO;
        [_titleRightBtn addTarget:self action:@selector(changeRightPage) forControlEvents:UIControlEventTouchUpInside];
        [_titleView addSubview:_titleRightBtn];
        
        //3.底部指示线view
        _titleFootView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_titleLeftBtn.frame), _titleLeftBtn.width, kCurrentScreenWidth(2))];
        _titleFootView.backgroundColor = KYColor(237, 106, 45, 1.0);
        [_titleView addSubview:_titleFootView];
        
        //4.中间分隔view
        UIView *sepertateView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_titleLeftBtn.frame), kCurrentScreenWidth(3), 1, _titleLeftBtn.height - kCurrentScreenWidth(6))];
        sepertateView.backgroundColor = KYColor(237, 106, 45, 1.0);
        [_titleView addSubview:sepertateView];
    }
    return _titleView;
}

- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.titleView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.titleView.frame) - 49)];
        _scrollView.delegate = self;
        _scrollView.contentSize = CGSizeMake(kScreenWidth * 2, 0);
        _scrollView.autoresizesSubviews = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}

- (UITableView *)thelatestTabView
{
    if (!_thelatestTabView) {
        _thelatestTabView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, self.scrollView.height) style:UITableViewStyleGrouped];
        _thelatestTabView.delegate = self;
        _thelatestTabView.dataSource = self;
        _thelatestTabView.tableFooterView = [[UIView alloc] init];
        _thelatestTabView.sectionHeaderHeight = 0.1;
        _thelatestTabView.sectionFooterHeight = 0.1;
#warning - YES (数据请求)
        [_thelatestTabView addHeaderWithTarget:self action:@selector(leftRefreshData)];
        [_thelatestTabView addFooterWithTarget:self action:@selector(leftReloadOtherData)];
    }
    return _thelatestTabView;
}

- (UITableView *)thehottestTabVeiw
{
    if (!_thehottestTabVeiw)
    {
        _thehottestTabVeiw = [[UITableView alloc] initWithFrame:CGRectMake(kScreenWidth, 0, kScreenWidth, self.scrollView.height) style:UITableViewStyleGrouped];
        _thehottestTabVeiw.delegate = self;
        _thehottestTabVeiw.dataSource = self;
        _thehottestTabVeiw.tableFooterView = [[UIView alloc] init];
        _thehottestTabVeiw.sectionHeaderHeight = 0.1;
        _thehottestTabVeiw.sectionFooterHeight = 0.1;
#warning - YES (数据请求)
        [_thehottestTabVeiw addHeaderWithTarget:self action:@selector(rightRefreshData)];
        [_thehottestTabVeiw addFooterWithTarget:self action:@selector(rightReloadOtherData)];
    }
    return _thehottestTabVeiw;
}

- (UIImageView *)leftFailImageView
{
    if (!_leftFailImageView)
    {
        _leftFailImageView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - kNewCurrentScreen(175))/2, (kScreenHeight - kNewCurrentScreen(143))/2, kNewCurrentScreen(175), kNewCurrentScreen(143))];
        _leftFailImageView.image = [UIImage imageNamed:@"state_dynamic_bg"];
    }
    return _leftFailImageView;
}

- (UIImageView *)rightFailImageView
{
    if (!_rightFailImageView)
    {
        _rightFailImageView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - kNewCurrentScreen(175))/2, (kScreenHeight - kNewCurrentScreen(143))/2, kNewCurrentScreen(175), kNewCurrentScreen(143))];
        _rightFailImageView.image = [UIImage imageNamed:@"state_dynamic_bg"];
    }
    return _rightFailImageView;
}

#pragma mark - method(刷新请求数据／加载更多)
- (void)rightRefreshData
{
    _hotPageIndex = 1;
    _hotPageSize = 5;
    [self requestListData:kHotStatus];
}

- (void)rightReloadOtherData
{
    _hotPageIndex++;
    [self requestListData:kHotStatus];
}

- (void)leftRefreshData
{
    _newPageSize = 5;
    _newPageIndex = 1;
    [self requestListData:kNewStatus];
}

- (void)leftReloadOtherData
{
    _newPageIndex++;
    [self requestListData:kNewStatus];
}
@end
